import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/device.dart';
import '../../providers/auth_provider.dart';
import '../../providers/device_provider.dart';
import 'widgets/device_list.dart';
import 'device_detail_screen.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  bool _isInit = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!_isInit) {
      _fetchDevices();
      _isInit = true;
    }
  }

  Future<void> _fetchDevices() async {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final deviceProvider = Provider.of<DeviceProvider>(context, listen: false);
    
    if (authProvider.user != null) {
      await deviceProvider.fetchDevices(authProvider.user!);
    }
  }

  void _handleToggleDevice(String deviceId, bool status) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final deviceProvider = Provider.of<DeviceProvider>(context, listen: false);
    
    if (authProvider.user != null) {
      deviceProvider.toggleDeviceStatus(authProvider.user!, deviceId, status);
    }
  }

  void _handleDeviceSelected(String deviceId) {
    final deviceProvider = Provider.of<DeviceProvider>(context, listen: false);
    final selectedDevice = deviceProvider.devices.firstWhere(
      (device) => device.id == deviceId,
    );
    
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => DeviceDetailScreen(device: selectedDevice),
      ),
    );
  }

  void _handleLogout() {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    authProvider.logout();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('智能家居'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _fetchDevices,
          ),
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: _handleLogout,
          ),
        ],
      ),
      body: Consumer<DeviceProvider>(
        builder: (context, deviceProvider, child) {
          if (deviceProvider.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          
          if (deviceProvider.error != null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '加载设备失败: ${deviceProvider.error}',
                    textAlign: TextAlign.center,
                    style: const TextStyle(color: Colors.red),
                  ),
                  const SizedBox(height: 16.0),
                  ElevatedButton(
                    onPressed: () {
                      deviceProvider.clearError();
                      _fetchDevices();
                    },
                    child: const Text('重试'),
                  ),
                ],
              ),
            );
          }
          
          return RefreshIndicator(
            onRefresh: _fetchDevices,
            child: DeviceList(
              devices: deviceProvider.devices,
              onToggleDevice: _handleToggleDevice,
              onDeviceSelected: _handleDeviceSelected,
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 添加新设备的功能（可以在后续实现）
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('添加设备功能将在后续版本中实现')),
          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}